//
// Created by Japhy on 2017-8-29.
//

#include <jni.h>
#include <string>

#define LOG_TAG "jni"
#include "alog.h"
//#include "UsbHostManager.h"
#include "usb.h"
#include "ccid.h"

extern "C"{

JNIEXPORT jint JNICALL Java_lc_com_pcsc_Pcsc_native_1init
        (JNIEnv *env, jclass cls){
    //UshHostManager_Init((void*)0);
    usb_init((void*)0);
    return 0;
}

JNIEXPORT jstring JNICALL Java_lc_com_pcsc_Pcsc_native_1get_1device
        (JNIEnv *env, jclass cls){
    const char* text = usb_is_present() ? "device present" : "device absent";
    return env->NewStringUTF(text);
}

/*
 * Class:     lc_com_pcsc_Pcsc
 * Method:    native_connect
 * Signature: ([B)I
 */

JNIEXPORT jint JNICALL Java_lc_com_pcsc_Pcsc_native_1connect
        (JNIEnv *env, jclass clazz, jbyteArray buffer){

    uint8_t atr[32];
    uint32_t alen = 0;
    //int ret;

    LOGD(__FUNCTION__);

    jbyte* bufferBytes = NULL;
    if (buffer) {
        bufferBytes = (jbyte*)env->GetPrimitiveArrayCritical(buffer, NULL);
    }

    jint ret = ccid_connect((uint8_t*)bufferBytes, &alen);

    if (bufferBytes) {
        env->ReleasePrimitiveArrayCritical(buffer, bufferBytes, 0);
    }

    return ret;
}

/*
 * Class:     lc_com_pcsc_Pcsc
 * Method:    native_exchange
 * Signature: ([B[B)I
 */

JNIEXPORT jint JNICALL Java_lc_com_pcsc_Pcsc_native_1exchange
        (JNIEnv *, jclass, jbyteArray, jbyteArray){
    int ret;
    uint8_t capdu[256] = {0x00, 0x84, 0x00, 0x00, 0x08};
    uint32_t clen = 5;
    uint8_t rapdu[256];
    uint32_t rlen = 0;

    LOGD(__FUNCTION__);

    ret = ccid_exchange(capdu, clen, rapdu, &rlen);
    return ret;
}

/*
 * Class:     lc_com_pcsc_Pcsc
 * Method:    native_disconnect
 * Signature: ()I
 */

JNIEXPORT jint JNICALL Java_lc_com_pcsc_Pcsc_native_1disconnect
        (JNIEnv *, jclass){
    LOGD(__FUNCTION__);
    return ccid_disconnect();
}

/*
 * Class:     lc_com_pcsc_Pcsc
 * Method:    native_slot_status
 * Signature: ()I
 */

JNIEXPORT jint JNICALL Java_lc_com_pcsc_Pcsc_native_1slot_1status
        (JNIEnv *, jclass){
    LOGD(__FUNCTION__);
    return ccid_slot_status();
}

}